package com.leigq.www.consumer.config;

import com.leigq.www.common.enumeration.QueueEnum;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 队列相关配置，JavaConfig 方式，本项目使用的是全注解方式，JavaConfig 仅仅作为参考
 * <br/>
 *
 * @author ：leigq
 * @date ：2019/7/25 20:14
 */
@Configuration
public class QueueConfig {

    /**
     * 错误消息的队列
     *
     * @return the queue
     */
    @Bean
    public Queue errorQueue() {
        return QueueBuilder
                .durable(QueueEnum.ERROR_QUEUE.getQueueName())
                .build();
    }

	/**
     * 错误消息的交换机
     * <br/>
     * 消费重试达到最大次数后仍不能被消费的，将会投递到此交换机
     *
     * @return the direct exchange
     */
    @Bean
    public DirectExchange errorExchange() {
        return (DirectExchange) ExchangeBuilder.directExchange(QueueEnum.ERROR_QUEUE.getExchangeName())
                .durable(true)
                .build();
    }

    /**
     * 错误消息队列绑定错误消息交换机
     *
     * @param errorQueue    the error queue
     * @param errorExchange the error exchange
     * @return the binding
     */
    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorExchange) {
        return BindingBuilder.bind(errorQueue)
                .to(errorExchange)
                .with(QueueEnum.ERROR_QUEUE.getRoutingKey());
    }

    /**
     * 消息恢复器
     *
     * @param rabbitTemplate the rabbit template
     * @return the message recoverer
     */
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, QueueEnum.ERROR_QUEUE.getExchangeName(), QueueEnum.ERROR_QUEUE.getRoutingKey());
    }

}
